package com.fiberhome.nas.feature.photo.viewmodel

import android.content.Context
import androidx.lifecycle.viewModelScope
import com.fiberhome.nas.core.common.base.viewmodel.BaseViewModel
import com.fiberhome.nas.core.data.repository.AlbumRepository
import com.fiberhome.nas.core.data.state.AppState
import com.fiberhome.nas.core.model.entity.AlbumInfo
import com.fiberhome.nas.core.model.entity.LocalAlbum
import com.fiberhome.nas.core.model.entity.LocalMediaItem
import com.fiberhome.nas.core.result.ResultHandler
import com.fiberhome.nas.core.result.asResult
import com.fiberhome.nas.core.util.media.MediaUtils
import com.fiberhome.nas.core.util.toast.ToastUtils
import com.fiberhome.nas.feature.common.manager.UploadManager
import com.fiberhome.nas.navigation.AppNavigator
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject


@HiltViewModel
class PhotoUploadViewModel @Inject constructor(
    appState: AppState,
    navigator: AppNavigator,
    @ApplicationContext private val context: Context,
    private val albumRepository: AlbumRepository,
    private val uploadManager: UploadManager  // 注入UploadManager
) : BaseViewModel(navigator, appState) {

    private val _selectedIds = MutableStateFlow<Set<Long>>(emptySet())
    val selectedIds: StateFlow<Set<Long>> = _selectedIds.asStateFlow()

    private val _photos = MutableStateFlow<List<LocalMediaItem>>(emptyList())
    val photos: StateFlow<List<LocalMediaItem>> = _photos.asStateFlow()

    private val _localAlbums = MutableStateFlow<List<LocalAlbum>>(emptyList())
    val localAlbums: StateFlow<List<LocalAlbum>> = _localAlbums.asStateFlow()

    private val _deviceAlbums = MutableStateFlow<List<AlbumInfo>>(emptyList())
    val deviceAlbums: StateFlow<List<AlbumInfo>> = _deviceAlbums.asStateFlow()


    fun initData() {
        loadDeviceAlbums()
        viewModelScope.launch {
            loadLocalAlbums()
            loadPhotos(localAlbums.value.first().bucketId)
        }
    }

    /**
     * 加载照片
     */
    suspend fun loadPhotos(bucketId: String) {
        val mediaItems = MediaUtils.getInstance(context).getMediaItemsByAlbum(bucketId)
        _photos.emit(mediaItems)
    }

    /**
     * 加载本地相册
     */
    suspend fun loadLocalAlbums() {
        val albums = MediaUtils.getInstance(context).getAllAlbums()
        _localAlbums.emit(albums)
    }

    /**
     * 加载设备相册
     */
    fun loadDeviceAlbums() {
        ResultHandler.handleResultWithData(
            scope = viewModelScope,
            flow = albumRepository.getAlbumList().asResult(),
            onData = { data ->
                _deviceAlbums.value = data.items.sortedBy { it.id.toInt() }
            }
        )
    }

    /**
     * 清空选中项
     */
    fun clearSelectedItems() {
        _selectedIds.update { emptySet() }
    }

    /**
     * 切换全选状态
     *
     * @param select 全选状态
     */
    fun toggleSelectAll(select: Boolean) {
        _selectedIds.update {
            if (select) photos.value.map { it.id }.toSet() else emptySet()
        }
    }

    /**
     * 切换勾选状态
     *
     * @param ids 照片id列表
     * @param select 勾选状态
     */
    fun toggleItemsSelection(ids: List<Long>, select: Boolean) {
        _selectedIds.update {
            if (select) it + ids.toSet() else it - ids.toSet()
        }
    }

    /**
     * 上传选中照片
     *
     * @param deviceAlbum 设备相册
     */
    fun uploadSelectedPhotos(deviceAlbum: AlbumInfo) {
        val selectedPhotos = photos.value.filter { it.id in selectedIds.value }
        if (selectedPhotos.isNotEmpty()) {
            // 使用UploadManager上传选中照片
            uploadManager.uploadPhotos(selectedPhotos, deviceAlbum)
            ToastUtils.showSuccess("已添加${selectedPhotos.size}个文件到上传队列")
            // 清空选择
            clearSelectedItems()
            // 返回上一页
            navigateBack()
        } else {
            ToastUtils.showWarning("请选择要上传的照片")
        }
    }

    fun onSelectLocalAlbum(localAlbum: LocalAlbum) {
        viewModelScope.launch {
            loadPhotos(localAlbum.bucketId)
        }
    }
}

